{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ba63e0b8-87b7-499b-b9d9-1109a5935611",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.linear_model import LinearRegression, SGDRegressor\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "# 1. 准备数据\n",
    "x = np.array([[100],[113],[90],[89],[60],[70],[50],[45],[55],[78]])\n",
    "y = np.array([[301],[324],[285],[296],[200],[260],[300],[120],[180],[245]]).ravel()\n",
    "\n",
    "# 2. 划分训练集和测试集\n",
    "x_train, x_test, y_train, y_test = train_test_split(\n",
    "    x, y, test_size=0.3, random_state=42\n",
    ")\n",
    "\n",
    "# 3. 定义要比较的模型\n",
    "models = [\n",
    "    LinearRegression(),\n",
    "    SGDRegressor(loss='huber', max_iter=5000, random_state=42),\n",
    "    SGDRegressor(loss='squared_error', max_iter=5000, random_state=42),\n",
    "    SGDRegressor(loss='epsilon_insensitive', max_iter=5000, random_state=42)\n",
    "]\n",
    "names = ['LinearRegression', 'SGD_huber', 'SGD_squared_error', 'SGD_epsilon_insensitive']\n",
    "\n",
    "# 4. 定义要测试的正则化参数\n",
    "alphas = [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 50]\n",
    "scores = []\n",
    "\n",
    "# 5. 训练模型并记录得分\n",
    "for index, model in enumerate(models):\n",
    "    scores.append([])\n",
    "    for alpha in alphas:\n",
    "        if index > 0:  # 只对SGD模型设置alpha\n",
    "            model.set_params(alpha=alpha)\n",
    "        model.fit(x_train, y_train)\n",
    "        scores[index].append(model.score(x_test, y_test))\n",
    "\n",
    "# 6. 绘制结果\n",
    "fig = plt.figure(figsize=(10, 7))\n",
    "for i, name in enumerate(names):\n",
    "    plt.subplot(2, 2, i + 1)\n",
    "    plt.plot(range(len(alphas)), scores[i], 'g-')\n",
    "    plt.title(name)\n",
    "    print(f'{name}模型的最大预测准确率为: {max(scores[i]):.5f}')\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
